//
//  YGBanner.m
//  UIScrollView循环滚动_1
//
//  Created by wuyiguang on 15/9/6.
//  Copyright (c) 2015年 YG. All rights reserved.
//

#import "YGBanner.h"

@interface YGBanner () <UIScrollViewDelegate>
{
    UIScrollView    *_scrollView;
    UIPageControl   *_pageControl;
    
    UIImageView *_leftImageView;
    UIImageView *_centerImageView;
    UIImageView *_rightImageView;
    
    NSArray *_imageNames; // 图片的url
    
    NSTimer *_timer;
    
    CGSize _size; // Banner的大小
    
    NSInteger _curIndex; // 当前下标
}
@end

@implementation YGBanner

- (instancetype)initWithFrame:(CGRect)frame imageNames:(NSArray *)names imageHandle:(ImageHandle)block
{
    if (self = [super initWithFrame:frame])
    {
        
        NSAssert(names.count >= 3, @"Banner view imageNames 小于3");
        
        self.block = block;
        
        _size = frame.size;
        
        _imageNames = names;
        
        _curIndex = 0;
        
        // 创建UIScrollView
        [self instanceScrollView];
        
        // 创建UIPageContol
        [self instancePageControl];
        
        // 创建图片
        [self instanceImageViews];
        
        // 创建定时器
        [self instanceTimer];
    }
    return self;
}

- (void)instanceTimer
{
    // 开启定时器
    _timer = [NSTimer scheduledTimerWithTimeInterval:kIntervalTime target:self selector:@selector(autoScroll) userInfo:nil repeats:YES];
}

/**
 创建UIScrollView
 */
- (void)instanceScrollView
{
//    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, _size.width, _size.height)];
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    _scrollView.backgroundColor  = [UIColor blackColor];
    
    // 只有3屏
    _scrollView.contentSize = CGSizeMake(_scrollView.bounds.size.width * 3, _scrollView.bounds.size.height);
    
    _scrollView.showsHorizontalScrollIndicator = NO;
    
    _scrollView.pagingEnabled = YES;

    _scrollView.delegate = self;
    
    _scrollView.bounces = NO;
    
    [self addSubview:_scrollView];
    
    // 手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageHandle)];
    
    [_scrollView addGestureRecognizer:tap];
}

/**
 图片点击事件
 */
- (void)imageHandle
{
    if (self.block) {
        self.block(_curIndex);
    }
}

/**
 创建UIPageContol
 */
- (void)instancePageControl
{
    _pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, _size.height-30, _size.width, 30)];
    
    _pageControl.numberOfPages = _imageNames.count;
    
    _pageControl.enabled = NO;
    
    [self addSubview:_pageControl];
}

/**
 创建图片
 */
- (void)instanceImageViews
{
    for (int i = 0; i < 3; i++)
    {
        UIImageView *imageV = [[UIImageView alloc] initWithFrame:CGRectMake(_scrollView.bounds.size.width * i, 0, _scrollView.bounds.size.width, _scrollView.bounds.size.height)];
        
        imageV.contentMode = UIViewContentModeScaleAspectFit;
        
        [_scrollView addSubview:imageV];
        
        // 左边的图片
        if (0 == i)
        {
//            imageV.image = [UIImage imageNamed:[_imageNames lastObject]];
            [imageV sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",[_imageNames lastObject]]]];
            _leftImageView = imageV;
        }
        // 中间的图片
        else if (1 == i)
        {
//            imageV.image = [UIImage imageNamed:[_imageNames firstObject]];
            [imageV sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",[_imageNames firstObject]]]];
            _centerImageView = imageV;
        }
        // 右边的图片
        else
        {
//            imageV.image = [UIImage imageNamed:_imageNames[1]];
            [imageV sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",_imageNames[1]]]];
            _rightImageView = imageV;
        }
    }
    
    // 设置偏移，偏移到中间那张图
    [_scrollView setContentOffset:CGPointMake(_scrollView.bounds.size.width, 0) animated:NO];
}

/**
 自动滚屏
 */
- (void)autoScroll
{
    // 让scrollView显示在第下一个位置
    [_scrollView setContentOffset:CGPointMake(_scrollView.bounds.size.width*2, 0) animated:YES];
    
    [self reloadImage];
}

/**
 刷新图片
 */
- (void)reloadImage
{
    CGFloat offsetX = _scrollView.contentOffset.x;
    
    // 右边在滑动
    if (offsetX > _size.width)
    {
        _curIndex = (_curIndex + 1) % _imageNames.count;
    }
    // 左边在滑动
    else if (offsetX < _size.width)
    {
        _curIndex = (_curIndex + _imageNames.count - 1) % _imageNames.count;
    }
    
    // 左边的图片下标
    NSInteger leftCount = (_curIndex + _imageNames.count - 1) % _imageNames.count;
    
    /** 左边
     40123
     34012
     23401
     */
    
    /** 右边
     40123
     01234
     12340
     */
    
    // 右边的图片下标
    NSInteger rightCount = (_curIndex + 1) % _imageNames.count;
    
    [_leftImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",_imageNames[leftCount]]]];
    
    [_centerImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",_imageNames[_curIndex]]]];
    
    [_rightImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",_imageNames[rightCount]]]];
    
//    _leftImageView.image = [UIImage imageNamed:_imageNames[leftCount]];
//    
//    _centerImageView.image = [UIImage imageNamed:_imageNames[_curIndex]];
//    
//    _rightImageView.image = [UIImage imageNamed:_imageNames[rightCount]];
}

// 调整scrollView位置
- (void)changePosition
{
    // 交换ImgageView的位置
    [self reloadImage];
    
    _pageControl.currentPage = _curIndex;
    
    // 让scrollView始终显示在第1个位置
    [_scrollView setContentOffset:CGPointMake(_scrollView.bounds.size.width, 0) animated:NO];
}

#pragma mark - UIScrollView的代理

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self changePosition];
    
    // 重新启动定时器
    [self instanceTimer];
    
    // 打开定时器
//    [_timer setFireDate:[NSDate distantPast]];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    // 销毁定时器
    [_timer invalidate];
    
    // 关闭定时器
//    [_timer setFireDate:[NSDate distantFuture]];
}

// 当代码设置setContentOffset时调用，手势滑动不会调用
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    [self changePosition];
}

@end
